package com.raylu.realtime.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.flink.api.java.tuple.Tuple2;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.time.temporal.ValueRange;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Description:
 * <p>
 * Create by lucienoz on 2021/12/30.
 * Copyright © 2021 lucienoz. All rights reserved.
 */
public class PhoenixUtil {
    private static Properties load;

    private static Connection conn;

    static {
        try {
            conn = initConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Phoenix Connection 创建失败");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("config.prpperties load失败");
        }
    }

    public static Connection initConnection() throws SQLException, IOException {
        load = PropertiesUtil.load("config.properties");
        Connection connection = DriverManager.getConnection(load.getProperty("base.db.app.cdc.phoenix.url"));
        return connection;
    }

    public static <T> List<T> selectQuery(String querySql, Class<T> clazz) {
        ArrayList<T> arrayList = new ArrayList<T>();
        try (PreparedStatement preparedStatement = conn.prepareStatement(querySql)) {

            ResultSet resultSet = preparedStatement.executeQuery();
            for (; resultSet.next(); ) {
                T t = clazz.newInstance();
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    String columnName = resultSet.getMetaData().getColumnName(i);
                    Object value = resultSet.getObject(columnName);
                    BeanUtils.setProperty(t, columnName, value);
                }
                arrayList.add(t);
            }


        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Phoenix Sql:" + querySql + "执行出错");

        } catch (InstantiationException e) {
            e.printStackTrace();
            throw new RuntimeException("范型 T:" + clazz.getName() + "实例化出错InstantiationException");

        } catch (IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("范型 T:" + clazz.getName() + "实例化出错IllegalAccessException");
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException("BeanUtils:属性装载出错");
        }
        return arrayList;

    }

    public static void main(String[] args) {
        List<JSONObject> jsonObjects = selectQuery("select * from GMALL2021.DIM_SKU_INFO", JSONObject.class);

        for (JSONObject jsonObject : jsonObjects) {
            System.out.println(jsonObject);
        }


    }

}
